const indexDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB;
class IndexDBCache {
  // 构造函数
  constructor() {
    this.tableList = [
      {
        tableName: 'userList',
        key: 'id',
        indexKey: [
          {
            name: 'status',
            index: 'status'
          },
          {
            name: 'belong',
            index: 'belong'
          },
          {
            name: 'statusBelong',
            index: ['status', 'belong']
          },
        ]
      },
      // 订单聊天列表
      {
        tableName: 'messageList',
        key: 'fromTo',
        indexKey: ['name', 'to']
      },
      {
        tableName: 'messageItem',
        key: 'id',
        indexKey: [
          {
            name: 'fromTo',
            index: 'fromTo'
          },
          {
            name: 'fromToOnline',
            index: ['fromTo', 'onlineType']
          },

        ]
      },
      {
        tableName: 'messageGroupList',
        key: 'id',
        indexKey: ['title', 'owner']
      },
      // 聊天信息
      {
        tableName: 'messageGroupItem',
        key: 'id',
        indexKey: ['groupId']
      },
    ]
    this._db = null; //数据库
    this._transaction = null; //事务
    this._request = null;
    this._dbName = "chat"; //数据库名
    this._dbversion = 1; //数据库版本
    this.init = false
  }
  initDB() {
    if (this._db || this.init) {
      return
    }
    this.init = true
    return new Promise((resolve, reject) => {
      this._request = indexDB.open(this._dbName, this._dbversion); // 打开数据库
      // 数据库初始化成功
      this._request.onsuccess = (event) => {
        this._db = this._request.result;
        resolve(event);
      };
      // 数据库初始化失败
      this._request.onerror = (event) => {
        reject(event);
      };
      // 数据库初次创建或更新时会触发
      this._request.onupgradeneeded = (event) => {
        this._db = this._request.result;
        this.tableList.forEach(res => {
          if (!this._db.objectStoreNames.contains(res.tableName)) {
            let objectStore = this._db.createObjectStore(res.tableName, {
              keyPath: res.key
            });
            if (res.indexKey && res.indexKey.length > 0) {
              res.indexKey.forEach(index => {
                if (index.name) {
                  // 复合索引
                  objectStore.createIndex(index.name, index.index, {
                    unique: false
                  })
                } else {
                  objectStore.createIndex(index, index, {
                    unique: false
                  })
                }
              })
            }
          }
        })

      };
    });
  }
  closeDB() {
    this._db.close();
  }
  // 根据id修改数
  updateData(tableName, data) {
    return new Promise((resolve, reject) => {
      let request = this._db.transaction([tableName], 'readwrite') // 事务对象
        .objectStore(tableName) // 仓库对象
        .put(data)
      request.onsuccess = function (event) {
        resolve(event);
      }
      request.onerror = function (event) {
        console.log('数据更新失败')
        reject(event);
      }
    });
  }
  addData(tableName, params) {
    return new Promise((resolve, reject) => {
      let transaction = this._db.transaction(tableName, "readwrite");
      let store = transaction.objectStore(tableName);
      let response = store.add(params);
      // 操作成功
      response.onsuccess = (event) => {
        resolve(event);
      };
      // 操作失败
      response.onerror = (event) => {
        console.log("操作失败");
        reject(event);
      };
    });
  }
  // 通过主键读取数据
  getDataByKey(tableName, key) {
    return new Promise((resolve, reject) => {
      let transaction = this._db.transaction(tableName);
      let objectStore = transaction.objectStore(tableName);
      // 通过主键读取数据
      let request = objectStore.getAll(key);
      // 操作成功
      request.onsuccess = () => {
        resolve(request.result);
      };
      // 操作失败
      request.onerror = (event) => {
        reject(event);
      };
    });
  }
  // 根据索引获取数据
  getDataByIndex(tableName, indexName, key, page, pageSize) {
    return new Promise((resolve, reject) => {
      let list = [];
      let counter = 0; // 计数器
      let advanced = true; // 是否跳过多少条查询
      let transaction = this._db.transaction([tableName]) // 事务
      let objectStore = transaction.objectStore(tableName) // 仓库对象
      let keyRange = IDBKeyRange.only(key);
      if (key instanceof Array) {
        keyRange = key
      }
      const index = objectStore.index(indexName);
      const request = index.openCursor(keyRange, "prev");
      request.onerror = function (event) {
        console.log('事务失败')
        reject(event)
      }
      request.onsuccess = function (event) {
        let cursor = event.target.result;
        if (page && pageSize) {
          if (page > 1 && advanced) {
            advanced = false;
            cursor.advance((page - 1) * pageSize); // 跳过多少条
            return;
          }
          if (cursor) {
            // 必须要检查
            list.push(cursor.value);
            counter++;
            if (counter < pageSize) {
              cursor.continue(); // 遍历了存储对象中的所有内容
            } else {
              cursor = null;
              resolve(list)
            }
          } else {
            resolve(list)
          }
          // 没有分页查全部
        } else {
          if (cursor) {
            list.push(cursor.value) // 数据的处理就在这里。。。 [ 理解 cursor.key，cursor.primaryKey，cursor.value ]
            cursor.continue()
          } else {
            resolve(list)
          }
        }
      }
    });
  }
  // 清空表数据库数据
  clearDB(tableName) {
    return new Promise((resolve, reject) => {
      let transaction = this._db && this._db.transaction(tableName, "readwrite");
      let store = transaction && transaction.objectStore(tableName);
      let response = store && store.clear();
      transaction.oncomplete = (event) => {
        resolve(event);
      }
    });
  }
  // 删除数据库
  deleteDBAll() {
    let deleteRequest = indexDB.deleteDatabase(this._dbName);
    return new Promise((resolve, reject) => {
      deleteRequest.onerror = function (event) {
        console.log("删除失败");
      };
      deleteRequest.onsuccess = function (event) {
      };
    });
  }
  deleteDataById(tableName, id) {
    let request = this._db.transaction([tableName], 'readwrite').objectStore(tableName).delete(id)
    request.onsuccess = function () {

    }
    request.onerror = function () {
      console.log('数据删除失败')
    }
  }
  // 查询表的长度
  searchCount(tableName, indexName, key) {
    return new Promise((resolve, reject) => {
      let transaction = this._db.transaction([tableName]) // 事务
      let objectStore = transaction.objectStore(tableName) // 仓库对象
      if (indexName) {
        let keyRange = IDBKeyRange.only(key);
        if (key instanceof Array) {
          keyRange = key
        }
        const index = objectStore.index(indexName);
        const request = index.count(keyRange);
        request.onerror = function (event) {
          reject(0)
        }
        request.onsuccess = function (event) {
          let cursor = event.target.result;
          resolve(event.target.result)
        }
      } else {
        // 直接查表的长度
        var countRequest = objectStore.count();

        countRequest.onsuccess = function () {
          resolve(countRequest.result)
        };

        countRequest.onerror = function () {
          reject(0)
        };
      }

    });
  }
}
export default IndexDBCache;